package video_service

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"time"
)

var (
	appid   = "8364911036"
	token   = "zv5Z_YTIEyC8YNsXT9r-NGSETeknwWNQ"
	cluster = "volc_auc_common"
	//audioURL   = "http://vdept3.bdstatic.com/mda-rcaf1gaxd9hkxg5j/sc/cae_h264/1741693754958719515/mda-rcaf1gaxd9hkxg5j.mp4?v_from_s=hkapp-haokan-hbf&auth_key=1741758043-0-0-55f90fa8c460d68383aec8c75e912629&bcevod_channel=searchbox_feed&pd=1&cr=2&cd=0&pt=3&logid=2443148754&vid=7109424812305992935&klogid=2443148754&abtest=132219_1"
	serviceURL = "https://openspeech.bytedance.com/api/v1/auc"
	client     = &http.Client{}
)

type SubmitRequest struct {
	App       App       `json:"app"`
	User      User      `json:"user"`
	Audio     Audio     `json:"audio"`
	Additions Additions `json:"additions"`
}

type App struct {
	AppID   string `json:"appid"`
	Token   string `json:"token"`
	Cluster string `json:"cluster"`
}

type User struct {
	UID string `json:"uid"`
}

type Audio struct {
	Format string `json:"format"`
	URL    string `json:"url"`
}

type Additions struct {
	WithSpeakerInfo string `json:"with_speaker_info"`
}

func submitTask(audioURL string) string {
	request := SubmitRequest{
		App: App{
			AppID:   appid,
			Token:   token,
			Cluster: cluster,
		},
		User: User{
			UID: "388808087185088_demo",
		},
		Audio: Audio{
			Format: "wav",
			URL:    audioURL,
		},
		Additions: Additions{
			WithSpeakerInfo: "False",
		},
	}

	jsonData, err := json.Marshal(request)
	if err != nil {
		log.Fatal(err)
	}

	req, err := http.NewRequest("POST", serviceURL+"/submit", bytes.NewBuffer(jsonData))
	if err != nil {
		log.Fatal(err)
	}
	req.Header.Set("Authorization", "Bearer; "+token)
	req.Header.Set("Content-Type", "application/json")

	resp, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()

	body, _ := io.ReadAll(resp.Body)
	fmt.Println(string(body))

	var result struct {
		Resp struct {
			ID string `json:"id"`
		} `json:"resp"`
	}
	json.Unmarshal(body, &result)
	fmt.Println(result.Resp.ID)
	return result.Resp.ID
}

func queryTask(taskID string) map[string]interface{} {
	query := map[string]string{
		"appid":   appid,
		"token":   token,
		"id":      taskID,
		"cluster": cluster,
	}

	jsonData, _ := json.Marshal(query)
	fmt.Println(string(jsonData))

	req, err := http.NewRequest("POST", serviceURL+"/query", bytes.NewBuffer(jsonData))
	if err != nil {
		log.Fatal(err)
	}
	req.Header.Set("Authorization", "Bearer; "+token)
	req.Header.Set("Content-Type", "application/json")

	resp, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()

	body, _ := io.ReadAll(resp.Body)
	fmt.Println(string(body))

	var result map[string]interface{}
	json.Unmarshal(body, &result)
	return result
}

func fileRecognize(audioURL string) map[string]interface{} {
	taskID := submitTask(audioURL)
	startTime := time.Now()

	for {
		time.Sleep(2 * time.Second)
		resp := queryTask(taskID)

		code := int(resp["resp"].(map[string]interface{})["code"].(float64))

		if time.Since(startTime) > 300*time.Second {
			fmt.Println("wait time exceeds 300s")
			return nil
		}
		if code == 1000 {
			fmt.Println("success")
		} else if code < 2000 {
			fmt.Println("failed")
		}
		return resp
	}
}
